<template>
	<view class="waterfall-flow2-container" :style="{'padding': '0 '+ (offset || offsetO)}">
		<view class="waterfall-flow2-left" id="waterfallFlowLeft" :style="{'margin-right': offset || offsetW}">
			<slot name="left" v-bind:leftList="leftList"></slot>
		</view>
		<view class="waterfall-flow2-right" id="waterfallFlowRight">
			<slot name="right" v-bind:rightList="rightList"></slot>
		</view>
	</view>
</template>

<script>
	export default {
		name: 'waterfall-flow2',
		props: {
			list: {
				type: Array, // 列表数据
				default: []
			},
			offset: {
				type: String, // offset 是offsetW和offsetO的简写，也就是同时包含最外边的边距和元素之间的间距
				default: '' // 传有这个属性不为空时offsetW和offsetO将不生效
			},
			offsetW: {
				type: String, // offsetW => offset Within 外边距，两个元素的中间边距
				default: '10rpx'
			},
			offsetO: {
				type: String, // offsetO => offset Outside 外边距，两个元素的最外边边距
				default: ''
			}
		},
		data() {
			return {
				leftList: [],
				rightList: [],
				current: 0,
				isLoaded: true
			}
		},
		watch: {
			list: {
				immediate: true,
				handler(val) {
					// 数据追加，如果只是改变数据重新渲染，length长度一样，那么在这之前应该先调clear方法
					if (val.length > (this.leftList.length + this.rightList.length)) {
						if (!this.isLoaded) return
						this.isLoaded = false
						this.pushQueue()
					};
				}
			}
		},
		methods: {
			// 渲染队列
			pushQueue() {
				if ((this.leftList.length + this.rightList.length) >= this.list.length) {
					this.$emit('load', {
						total: this.current,
						leftList: this.leftList,
						rightList: this.rightList
					});
					this.isLoaded = true
					return;
				};
				
				setTimeout(() => {
					const query = uni.createSelectorQuery().in(this);
					query.select('#waterfallFlowLeft').boundingClientRect();
					query.select('#waterfallFlowRight').boundingClientRect();
					query.exec(res => {
						const leftHeight = res[0].height; // 获取左边列表的高度
						const rightHeight = res[1].height; // 获取右边列表的高度
						
						leftHeight <= rightHeight
							? this.leftList.push(this.list[this.current]) 
							: this.rightList.push(this.list[this.current]);

						this.current++;
						this.pushQueue(); // 执行下一个队列
					});
				}, 300);
			},
			// 清除数据，用于重新渲染
			clear() {
				this.leftList = [];
				this.rightList = [];
				this.current = 0;
			},
			// 额外导出的方法，用于更新数据或强制重新渲染
			update() {
				this.clear();
				this.$nextTick(() => {
					this.pushQueue();
				})
			}
		}
	}
</script>

<style scoped>
.waterfall-flow2-container {
	width: 100%;
	height: auto;
	display: flex;
	box-sizing: border-box;
}

.waterfall-flow2-left,
.waterfall-flow2-right {
	flex: 1;
	height: max-content;
}
</style>